package com.example.dangerouscargodriver.ui.fragment.tab;

import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.baiju.netmanager.Http.IHttpRequest;
import com.baiju.style.citylist.Toast.ToastUtils;
import com.example.dangerouscargodriver.R;
import com.example.dangerouscargodriver.controller.AuthController;
import com.example.dangerouscargodriver.entry.OrderStatusInfo;
import com.example.dangerouscargodriver.module.ResponseInfo;
import com.example.dangerouscargodriver.param.RemoteAPI;
import com.example.dangerouscargodriver.param.RemoteAPICmd;
import com.example.dangerouscargodriver.ui.fragment.HttpRequestFragment;
import com.example.dangerouscargodriver.ui.view.MultiListenerEditText;
import com.example.dangerouscargodriver.widget.BJPullToRefreshScrollView;
import com.example.dangerouscargodriver.widget.LoadingDialog;
import com.example.dangerouscargodriver.widget.OrderInfoView;
import com.example.dangerouscargodriver.widget.RequestMoreResourceInfoView;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.ScrollViewWithListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public abstract class OrderManagerTabFragment extends HttpRequestFragment {
    private static final String TAG = "OrderManagerTabAll";
    public static int TAB_ENUM_ALL = 0;
    public static int TAB_ENUM_DISCUSSING = 5;
    public static int TAB_ENUM_TRANSPORTING = 2;
    public static int TAB_ENUM_DONE = 3;
    public static int TAB_ENUM_CANCEL = 9;
    public static int TAB_ENUM_LOSE_EFFICACY = 4;

    private View mRootView = null;
    private LinearLayout mEmptyLayout = null;
    private List<OrderStatusInfo> mOrderInfo = null;
    private LinearLayout mLayoutContent = null;
    private BJPullToRefreshScrollView mScrollView = null;
    private RequestMoreResourceInfoView mRequestMore = null;
    private int mTotalOrderInfoNum = 0;

    private MultiListenerEditText mSearchResource = null;
    private String mKeyword = null;
    private TextWatcher mTextWatcher = null;
    private LoadingDialog mLoadingDialog = null;
    private MultiListenerEditText.OnEditorActionListener mListener = null;

    public OrderManagerTabFragment(){
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mOrderInfo = new ArrayList<>();
    }

    protected void initHttpComponent(java.lang.Class object){
        super.initHttpComponent(object);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mRootView =  inflater.inflate(R.layout.fragment_order_manager_tab_with_refresh, container, false);

        mEmptyLayout = mRootView.findViewById(R.id.layout_notice_empty);

        mLayoutContent = mRootView.findViewById(R.id.layout_content);
        mRequestMore = new RequestMoreResourceInfoView(getContext());
        mRequestMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLoadingDialog.show();
                executeSearchUserOrderInfo(false);
            }
        });
        mScrollView = mRootView.findViewById(R.id.layout_scroll_view);

        intRefreshScrollView();
        mLoadingDialog = new LoadingDialog(mRootView.getContext());
        mSearchResource = getActivity().findViewById(R.id.btn_search_resource);
        mKeyword = mSearchResource.getText().toString();
        mListener = new MultiListenerEditText.OnEditorActionListener(){

            @Override
            public void onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    mKeyword = mSearchResource.getText().toString();
                    mLoadingDialog.show();
                    executeSearchUserOrderInfo(true);
                }
            }
        };
        mSearchResource.addEditorActionListener(mListener);

        mTextWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if(mSearchResource.getText().toString().equals("")) {
                    mLoadingDialog.show();
                    mKeyword = "";
                    executeSearchUserOrderInfo(true);
                }
            }
        };
        mSearchResource.addTextChangedListener(mTextWatcher);

        return mRootView;
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        mLoadingDialog.show();
        executeSearchUserOrderInfo(true);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mSearchResource.removeEditorActionListener(mListener);
        mSearchResource.removeTextChangedListener(mTextWatcher);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    protected abstract int getOrderType();

    private void executeSearchUserOrderInfo(boolean refresh){
        HashMap<String, String> header = new HashMap<String, String>();
        header.put("token", AuthController.Instance().getToken());

        HashMap<String, String> param = new HashMap<String, String>();
        if(getOrderType() != TAB_ENUM_ALL){
            param.put("type", String.valueOf(getOrderType()));
        }
        if(mKeyword != null && !mKeyword.equals("")){
            param.put("keyword", mKeyword);
        }

        if(refresh) {
            mTotalOrderInfoNum = 0;
            mOrderInfo.clear();
            param.put("page", Integer.toString(1));
            sendHttpRequest(IHttpRequest.RequestMethod.GET_METHOD,
                    RemoteAPI.REQUEST_V2_USER_SR_ORDER,
                    header,
                    param,
                    RemoteAPICmd.REQUEST_V2_USER_SG_ORDER);
        }
        else{
            if(mOrderInfo.size() >= mTotalOrderInfoNum){
                ToastUtils.showLongToast(getContext(), "已无更多数据");
            }
            else {
                param.put("page", Integer.toString(mOrderInfo.size() / 10 + 1));
                sendHttpRequest(IHttpRequest.RequestMethod.GET_METHOD,
                        RemoteAPI.REQUEST_V2_USER_SR_ORDER,
                        header,
                        param,
                        RemoteAPICmd.REQUEST_V2_USER_SG_ORDER_PAGE);
            }
        }
    }

    private void refreshViewInFragment() {
        if(mOrderInfo != null && mOrderInfo.size() > 0) {
            mEmptyLayout.setVisibility(View.GONE);
            mLayoutContent.removeAllViews();
            for(int index = 0; index < mOrderInfo.size(); index++) {
                final int click = index;
                OrderInfoView view = new OrderInfoView(mRootView.getContext(),
                        mOrderInfo.get(index));
                view.bindData(mOrderInfo.get(index));
                mLayoutContent.addView(view);
            }

            mLayoutContent.addView(mRequestMore);
        }
        else{
            mEmptyLayout.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onHttpResponse(int actionId, String response) {
        try {
            JSONObject res = new JSONObject(response);
            Gson gson = new Gson();
            if(actionId == RemoteAPICmd.REQUEST_V2_USER_SG_ORDER){
                Log.d(TAG, "onResponse: " + response);
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1){
                    Type type = new TypeToken<List<OrderStatusInfo>>() {}.getType();
                    mOrderInfo = gson.fromJson(res.getJSONObject("data").getString("list"),
                            type);
                    mTotalOrderInfoNum = Integer.parseInt(res.getJSONObject("data").getString("count"));
                    refreshViewInFragment();
                }
                else{
                    /**/
                }
                mLoadingDialog.dismiss();
                refreshComplete();
            }
            else if(actionId == RemoteAPICmd.REQUEST_V2_USER_SG_ORDER_PAGE){
                ResponseInfo responseInfo = gson.fromJson(response, ResponseInfo.class);
                if(responseInfo != null && responseInfo.getStatus() == 1) {
                    Type type = new TypeToken<List<OrderStatusInfo>>() {
                    }.getType();
                    List<OrderStatusInfo> orderStatusInfos = gson.fromJson(res.getJSONObject("data").getString("list"),
                            type);
                    if(orderStatusInfos != null){
                        for (int index = 0; index < orderStatusInfos.size(); index++) {
                            mOrderInfo.add(orderStatusInfos.get(index));
                        }
                    }
                    refreshViewInFragment();
                }

                mLoadingDialog.dismiss();
            }
            else{

            }
        }
        catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onHttpErrorResponse(int actionId, String response) {
        if(actionId == RemoteAPICmd.REQUEST_V2_USER_SG_ORDER){
            refreshComplete();
        }

        mLoadingDialog.dismiss();
    }

    //进行初使化  （1.设置模式 2.通过getLoadingLayoutProxy方法设置header与footer的刷新显示文字 3.设置监听事件）
    private void intRefreshScrollView() {
        //1.设置模式
        mScrollView.setMode(PullToRefreshBase.Mode.PULL_FROM_START);

        //2.通过调用getLoadingLayoutProxy方法，设置下拉刷新状况布局中显示的文字 ，第一个参数为true,代表下拉刷新
        ILoadingLayout headLables = mScrollView.getLoadingLayoutProxy(true, false);
        headLables.setPullLabel("下拉刷新");
        headLables.setRefreshingLabel("正在刷新");
        headLables.setReleaseLabel("松开刷新");
/*
        //2.设置上拉加载底部视图中显示的文字，第一个参数为false,代表上拉加载更多
        ILoadingLayout footerLables = mScrollView.getLoadingLayoutProxy(false, true);
        footerLables.setPullLabel("上拉加载");
        footerLables.setRefreshingLabel("正在载入...");
        footerLables.setReleaseLabel("松开加载更多");
 */
        //3.设置监听事件
        mScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollViewWithListener>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollViewWithListener> refreshView) {
                //请求网络数据，并更新listview组件
                mLoadingDialog.show();
                executeSearchUserOrderInfo(true);
                //refreshComplete();//数据加载完成后，关闭header,footer
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollViewWithListener> refreshView) {
                //请求网络数据，并更新listview组件
                refreshComplete();//数据加载完成后，关闭header,footer
            }
        });

    }
    /**
     * 刷新完成时关闭
     */
    public void refreshComplete(){
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                mScrollView.onRefreshComplete();
            }
        },1000);
    }

}
